package cn.edu.hitsz.compiler.lexer;

// 代码阅读器
public class CodeReader {
    private char[] reader;
    private int index;
    private int line;

    public CodeReader(char[] reader) {
        this.reader = reader;
        this.index = 0;
        this.line = 1;
    }

    // 读取下一个字符
    public char next(){
        if(this.index < this.reader.length){
            // 检测换行
            if(reader[index] == '\n'){
                ++this.line;
            }
            return reader[index++];
        }
        else{
            throw new RuntimeException("Reader out of range!");
        }
    }

    // 读取上一个字符
    public char back(){
        if( (this.index - 1) < this.reader.length && this.index > 0){
            // 检测换行
            if(reader[this.index-1] == '\n'){
                --this.line;
            }
            return reader[--this.index];
        }
        else{
            throw new RuntimeException("Reader out of range!");
        }
    }

    // 判断是否读到末尾
    public boolean hasNext(){
        return (this.index < this.reader.length);
    }

    // 获取当前行数
    public int getLine() {
        return line;
    }
}
